import {defineStore} from "pinia";
import {loginApi,logOutApi} from "@/api/loginApi.js";
import {useRouter} from "vue-router";
import router from '@/router/index.js'
import {ElMessage} from "element-plus";

export const useUserStore = defineStore({
    id: 'user',
    state: () => ({
        userInfo: JSON.parse(localStorage.getItem("userInfo") || "{}"),
        token:localStorage.getItem('token') || ''
    }),
    getters: {
        getToken: (state) => state.userInfo.token
    },
    actions: {
        async loginAction(data) {
            const userInfo = await loginApi(data);
            ElMessage.success("登录成功！")
            localStorage.setItem("userInfo",JSON.stringify(userInfo));
            router.push('/')
            this.userInfo = userInfo;
        },
        async logoutAction(){
            await logOutApi();
            this.userInfo = {};
            localStorage.removeItem('userInfo')
            router.push('/login')
        }
    }
})